package fr.obsmip.sedoo.core.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import fr.obsmip.sedoo.core.domain.RBVUser;

@Repository
public class RBVUserDAOJPAImpl implements UserDAO{

	protected EntityManager em;
    public EntityManager getEntityManager() {
	        return em;
	    }

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
	        this.em = entityManager;
	    }

    @Override
	@Transactional
	public void delete(Long id) throws Exception {
		
		RBVUser user = getEntityManager().find(RBVUser.class, id);
		if (user != null)
		{
			getEntityManager().remove(user);
		}
	}

	@Override
	@Transactional
	public RBVUser save(RBVUser user) 
	{
		if (user.getId() == null)
		{
			getEntityManager().persist(user);
			return user;
		}
		else
		{
			getEntityManager().merge(user);
			return user;
		}
	}

	@Override
	public ArrayList<RBVUser> findAll() {
		List<RBVUser> aux = em.createQuery("select format from RBVUser rbvUser").getResultList();
		ArrayList<RBVUser> resultList = new ArrayList<RBVUser>();
		resultList.addAll(aux);
		return resultList;
	}

	@Override
	public RBVUser login(String login, String password) throws Exception 
	{
		
		String query = "select rbvUser from RBVUser as rbvUser where rbvUser.login='"+login+"' and rbvUser.password='"+password+"'";
		List<RBVUser> aux = em.createQuery(query).getResultList();
		if (aux.isEmpty())
		{
			throw new Exception();
		}
		else
		{
			return aux.iterator().next();
		}
	}
	
	@Override
	public RBVUser getExternallyAuthenticatedUser(String login) throws Exception 
	{
		String query = "select rbvUser from RBVUser as rbvUser where rbvUser.login='"+login+"'";
		List<RBVUser> aux = em.createQuery(query).getResultList();
		if (aux.isEmpty())
		{
			throw new Exception("Unknown user");
		}
		else
		{
			return aux.iterator().next();
		}
	}

	
	

	

}
